package com.offcn.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;

/**
 * @description: TODO
 * @author: LongChen
 * @date: 2022/8/7 16:59
 * @version: 1.0
 */

public class JWTUtil {

    //秘钥
    private static final String SECRET_KEY = "u-member-offcn123";
    //token过期时间
    public static final long TOKEN_EXPIRE_TIME = 5 * 60 * 1000;
    //refreshToken过期时间
    public static final long REFRESH_TOKEN_EXPIRE_TIME = 10 * 60 * 1000;
    //签发人
    private static final String ISSUER = "longchen";

    //生成签名
    public static String generateToken(String username){
        Date now = new Date();
        return   Jwts.builder()
                //签发人
                .setIssuer(ISSUER)
                //签发时间
                .setIssuedAt(now)
                //过期时间
                .setExpiration(new Date(now.getTime()+TOKEN_EXPIRE_TIME))
                //用户名
                .claim("username",username)
                //签名算法、秘钥
                .signWith(SignatureAlgorithm.HS256,SECRET_KEY)
                .compact();
    }

    //解析token
    private static Claims parseToken(String token){
        return    Jwts.parser()
                .setSigningKey(SECRET_KEY)
                .parseClaimsJws(token).getBody();
    }

    //验证签名
    public static boolean verify(String token){
        //尝试解析token
        try {
            Claims claims = parseToken(token);
            return true;

        } catch (Exception e) {
            // e.printStackTrace();
            System.out.println("签名验证失败");
            return false;
        }
    }

    //从token获取用户名
    public static String getUsername(String token){
        try {
            Claims claims = parseToken(token);
            String username = (String) claims.get("username");
            return username;
        } catch (Exception e) {
            // e.printStackTrace();
            System.out.println("解析令牌失败");
            return "";
        }
    }

}
